#!/usr/bin/env bash

set -e

function k3d-cluster-delete {
    if [ -z "$1" ]; then
        return
    fi

    k3d cluster delete "$1"
}

function docker-clean-by-name {
    if [ -z "$1" ]; then
        return
    fi

    ids=$(docker ps -a --filter name="$1" --format "{{.ID}}")
    if [ -z "$ids" ]; then
        return
    fi

    for id in $ids; do
        docker stop "$id"
        docker rm "$id"
    done
}

if [[ -n "$FLEET_E2E_CLUSTER" || -n "$FLEET_E2E_CLUSTER_DOWNSTREAM" ]]; then
    k3d-cluster-delete "$FLEET_E2E_CLUSTER"
    k3d-cluster-delete "$FLEET_E2E_CLUSTER_DOWNSTREAM"

    docker-clean-by-name "$FLEET_E2E_CLUSTER"
    docker-clean-by-name "$FLEET_E2E_CLUSTER_DOWNSTREAM"
else
    configs=(
        dev/env.single-cluster-defaults
        dev/env.multi-cluster-defaults
    )
    for config in "${configs[@]}"; do
        # shellcheck source=/dev/null
        source "$config"

        config_vars=(
            "$FLEET_E2E_CLUSTER"
            "$FLEET_E2E_CLUSTER_DOWNSTREAM"
        )

        for config_var in "${config_vars[@]}"; do
            k3d-cluster-delete "$config_var"
            docker-clean-by-name "$config_var"
        done
    done
fi

docker-clean-by-name "act"
